<template>
  <div class="table-content posf" v-bind:class="{hide: !show}">
    <div class="picker" aria-hidden="true" role="menuitem">
      <div class="table-content-main" v-on:mousemove="mousemove">
        <div class="picker-mousecatcher" v-bind:style="totalStyle"></div>
        <div class="picker-unhighlighted" v-bind:style="bgStyle"></div>
        <div class="picker-highlighted" v-bind:style="selectedStyle" v-on:click="click"></div>
      </div>
      <div class="picker-status">&#8234;{{x}} x {{y}}&#8236;</div>
    </div>
  </div>
</template>

<script>
  import { mapState, mapGetters } from 'vuex'
  import {Observer} from '../../core/util'
  export default {
    data: function () {
      return {
          show: false,
          maxX: 20,
          maxY: 20,
          minX: 5,
          minY: 5,
          x: 1,
          y: 1
      }
    },
    created: function () {
      var self = this;
      Observer.register('showtablepicker', function () {
        self.x = 1;
        self.y = 1;
        self.show = true;
      });
      Observer.register('hidecloth', function () {
        self.show = false;
      });
    },
    computed: {
      totalStyle: function () {
        return {
          width: this.maxX + 'em',
          height: this.maxY + 'em'
        }
      },
      bgStyle: function () {
        return {
          width: (this.x >= this.maxX ? this.maxX : (this.x < this.minX ? this.minX : this.x + 1)) + 'em',
          height: (this.y >= this.maxY ? this.maxY : (this.y < this.minY ? this.minY : this.y + 1)) + 'em'
        }
      },
      selectedStyle: function () {
        return {
          width: this.x + 'em',
          height: this.y + 'em'
        }
      }
    },
    methods: {
      click: function () {
        this.show = false;
        Observer.fire('hidecloth');
        Observer.fire('execCommand', ['InsertTable', {
          numCols: this.x,
          numRows: this.y
        }]);
      },
      mousemove: function (e) {
        var total = this.$el.querySelector('.picker-mousecatcher');
        this.x = (e.offsetX === undefined ? e.layerX : e.offsetX / total.offsetWidth * 20 | 0) + 1;
        this.y = (e.offsetY === undefined ? e.layerY : e.offsetY / total.offsetHeight * 20 | 0) + 1;
      }
    }
  }
</script>